const router = require('koa-router')()
const path = require("path");
var svgCaptcha = require('svg-captcha');
svgCaptcha.height = 40;
var nowCaptcha;
var jwt = require("jsonwebtoken");
const { IncomingForm } = require('formidable');
const mykey = "shidaihaodang";
const formidable = require("formidable");
const fs = require("fs");

const cheakToken = require("../static/checkToken");

const url = path.join(__dirname, "../public/upload");

const avatarUrl = path.join(__dirname, "../public/avatar");

let selectALL = "select image_name from image"

let fileList = fs.readdirSync(url);

// 已修改
function readfile(ctx) {
  return new Promise(async (rv, rj) => {
      // console.log("shidoa");
      let url = path.join(__dirname, "../public/upload");
      let result1 = await ctx.db.EXCUTE(selectALL, []);
      console.log(result1);
      let form = formidable({
          uploadDir: url,
          keepExtensions: true,
          multiples: true
      })
      form.parse(ctx.req, async (err, fields, files) => {
        console.log("shidaohaodang");
          if(err) {
          } else {
              for(let item in files) {
                let count = 0;
                for(let i in result1) {
                  console.log(result1[i]);
                  if(result1[i].image_name == files[item].originalFilename) {
                    console.log(result1[i], "123456798");
                    count++
                  }
                }
                fileList.unshift(files[item].originalFilename)
                console.log(count, "count:");
                let sql = "insert into image (image_name, image_size, image_type, image_path) values (?, ?, ?, ?)";
                if(count > 0) {
                  let name = files[item].originalFilename;
                  let arr = name.split('.');
                  arr[0]  += count;
                  name = arr.join('.');
                  let result = await ctx.db.EXCUTE(sql, [name, files[item].size, files[item].mimetype, "http://localhost:3000/getFile/" + name]);
                  console.log(result);
                  fs.renameSync(files[item].filepath, path.join(url, name));
                } else {
                  let result = await ctx.db.EXCUTE(sql, [files[item].originalFilename, files[item].size, files[item].mimetype, "http://localhost:3000/getFile/" + files[item].originalFilename]);
                  console.log(result);
                  fs.renameSync(files[item].filepath, path.join(url, files[item].originalFilename));
                }
              }
          }
          rv(123);
      })
  })
}
// 上传头像
function readAvatar(ctx) {
  return new Promise(async (rv, rj) => {
      // console.log("shidoa");
      let url = path.join(__dirname, "../public/avatar");
      let sql = "select user_avatar from users where user_id = ?";
      let sql1 = "update users set user_avatar = ? where user_id = ?"
      let result1 = await ctx.db.EXCUTE(sql, [ctx.params.id]);
      console.log(result1);
      let form = formidable({
          uploadDir: url,
          keepExtensions: true,
          multiples: true
      })
      form.parse(ctx.req, async (err, fields, files) => {
        console.log("shidaohaodang");
          if(err) {
          } else {
            // if()
            let res = await ctx.db.EXCUTE(sql1, [files[0].originalFilename, ctx.params.id]);
            console.log(res);
            console.log(files);
            fs.renameSync(files[0].filepath, path.join(url, files[0].originalFilename));
            ctx.body = {code: "200", msg: "上传成功", url: files[0].originalFilename}

          }
          rv(123);
      })
  })
}


router.get("/getAuth", async (ctx, next) => {
  let option = {
    size: 4,
    noise: 1,
    color: true,
    height: 40
  }
  var captcha = svgCaptcha.create(option);
  nowCaptcha = captcha;
  console.log(captcha.text);
  ctx.session.captcha = captcha.text;
  ctx.body = nowCaptcha;
})

router.get("/getAvatar/:id", async (ctx, next) => {
  console.log(ctx);
  let url = path.join(__dirname, "../public/avatar/" + ctx.params.id);
  let data = fs.readFileSync(url);
  ctx.body = data;
});

router.post("/getList" , async(ctx, next) => {
  console.log(ctx.request.body);
  let page = ctx.request.body.page; 
  let arr = await getImgInfo(ctx);
  let length = arr.length;
  let obj = {code: 200, msg: "成功获取数据" , infoList: arr.slice((page - 1) * 10 , page * 10) , total: length}
  ctx.body = obj;
});

// 已修改
router.post("/submit" , async (ctx, next) => {
  console.log(ctx.request.body);
  console.log(nowCaptcha);
  let sql = "select user_name, user_password from users"
  let result = await ctx.db.EXCUTE(sql, []);
  let sql1 = "select * from users where user_name = ? and user_password = ?"
  console.log(result);
  if(nowCaptcha.text === ctx.request.body.auth) {
    if(result.find(item => {
      console.log(item);
      return item.user_name === ctx.request.body.username && item.user_password === ctx.request.body.password
    })) {
      let token = jwt.sign({username: ctx.request.body.username, authority: true}, mykey);
      let res = await ctx.db.EXCUTE(sql1, [ctx.request.body.username, ctx.request.body.password]);
      ctx.body = {code: 200, type: "success", message: "登录成功", token, userInfo: res};
    } else {
      ctx.body = {code: 500, type: "error", message: "用户名或密码错误"}
    }
  } else{
    ctx.body = {code: 500, type: "error", message: "验证码错误"}
  }
})

// 已修改
router.post("/sendPic", async (ctx, next) => {
  let checkRes = await checkToken.cheakToken(ctx);
  if(checkRes) {
    await readfile(ctx).then(async res => {
      console.log(123456789);
    })
    let infoList = await getImgInfo(ctx);
    ctx.body = {code: "200", message: "success", infoList}
  } else {
      ctx.body = {code: "500", msg: "请先登录"}
  }
})


router.get("/getImg" , async (ctx, next) => {
  let url = path.join(__dirname, "../public/upload");
  let list = fs.readdirSync(url);
  ctx.body = list;
})

router.get("/getFile/:id" , async(ctx, next) => {
  let url = path.join(__dirname, "../public/upload");
  ctx.body = fs.readFileSync(path.join(url, ctx.params.id));
})

router.get("/getlist", async(ctx, next) => {
  ctx.body = await getImgInfo(ctx);
})

const getImgInfo = async(ctx) => {
  let sql = "select * from image";
  let result = await ctx.db.EXCUTE(sql, []);
  return result.reverse();
}

router.post("/deleteImg", async(ctx, next) => {
  let checkRes = await checkToken.cheakToken(ctx);
  if(checkRes) {
    let url = path.join(__dirname, "../public/upload");
    let sql = "delete from image where image_name = ?";
    let result = await ctx.db.EXCUTE(sql, [ctx.request.body.name]);
    console.log(result);
    // fileList.splice(fileList.indexOf(ctx.request.body.name), 1)
    fs.unlinkSync(path.join(url, ctx.request.body.name))
    let infoList = await getImgInfo(ctx);
    ctx.body = {code: 200, msg: "成功删除", infoList}
  } else {
      ctx.body = {code: "500", msg: "请先登录"}
  }
})

router.post("/uploadImg/:id", async (ctx, next) => {
  console.log(ctx.params.id);
  console.log(ctx.request.body);
  
  // console.log(ctx.request.body.get("userId"))
  await readAvatar(ctx).then(async res => {
    console.log(123456789);
  })
  
})



module.exports = router
